//
//  BudgetEdit.swift
//  Speek
//
//  Created by MikeHo on 2023/6/29.
//

import SwiftUI
import CoreData

struct BudgetEdit: View {
    
    let budgetTypeArray = ["学习","医疗","饮食","维修","旅行","运动","娱乐","购物","理财","其他"]
    let year : String
    let month : String
    @Binding var isEditSuccess : Bool
    @State private var selectType : String = "学习"
    @State private var inputAmount : Double = 0.0
    
    @Environment(\.dismiss) private var dismiss
    @Environment(\.managedObjectContext) private var context
    
    var body: some View {
        NavigationStack{
            HStack{
                Section("种类"){
                    Picker(selection: $selectType,
                           label: Image(selectType)
                        .padding(.leading,5)){
                            ForEach(budgetTypeArray,id:\.self){type in
                                HStack{
                                    Text(type)
                                        .font(.body)
                                    Spacer()
                                    Image(type)
                                       // .scaledToFit()
                                        .frame(width:30,height:30)
                                        .aspectRatio(contentMode: .fill)

                                }
                                //.padding(.vertical,70)
                            }
                        }
                        .frame(height:200)
                        .pickerStyle(WheelPickerStyle())
                    
                    }
                Section("预算金额"){
                    TextField(value:$inputAmount,formatter: currencyFormatter){}
                        .labelsHidden()
                        .keyboardType(.decimalPad)
                        .background(Color.gray.opacity(0.2).cornerRadius(5))
                }
            }
            .padding(.horizontal,20)
            .frame(height:400)
            .preferredColorScheme(.dark)
            .navigationTitle("编辑预算")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar{
                ToolbarItem(placement: .navigationBarTrailing){
                    Button("更新"){
                        updateBudgetAmount(year: year, month: month, type: selectType, amount: inputAmount)
                        isEditSuccess = true
                    }
                }
                ToolbarItem(placement: .navigationBarLeading){
                    Button("完成"){
                        dismiss()
                    }
                }
            }
            .alert(isPresented: $isEditSuccess) {
                return Alert(
                    title: Text("Budget Edit"),
                               message: Text("预算编辑成功"),
                    dismissButton: .default(Text("OK")) {
                        isEditSuccess = false
                    }
                )
            }
        }
        
    }
    
    private func updateBudgetAmount(year: String, month: String, type: String, amount: Double) {
        
        // 创建一个FetchRequest来检索符合条件的BudgetDetail对象
        let fetchRequest: NSFetchRequest<BudgetDetail> = BudgetDetail.fetchRequest()
        fetchRequest.predicate = NSPredicate(format: "year == %@ AND month == %@ AND type == %@", argumentArray: [year, month, type])
        
        do {
            // 执行FetchRequest，检索符合条件的BudgetDetail对象
            let results = try context.fetch(fetchRequest)
            
            // 修改预算金额
            if let budget = results.first {
                budget.amount = amount
            }
            
            // 保存上下文以将更改持久化到Core Data
            try context.save()
                        
        } catch {
            // 处理错误
            print("Failed to update budget amount: \(error)")
        }
    }
}
